package com.ruoyi.common.utils;

import java.lang.management.ManagementFactory;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import com.ruoyi.common.config.Global;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;


/**
 * 时间工具类
 *
 * @author ruoyi
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
    private static final Logger log = LoggerFactory.getLogger(DateUtils.class);
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";


    private static String[] parsePatterns = {"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM", "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss",
            "yyyy.MM.dd HH:mm", "yyyy.MM"};
    @Autowired
    private Global global;

    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate() {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate() {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime() {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow() {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format) {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date) {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStrEmpty(final String format, final Date date) {
        if (null == date) {
            return null;
        }
        return new SimpleDateFormat(format).format(date);
    }

    public static final String parseDateToStr(final String format, final Date date) {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts) {
        try {
            return new SimpleDateFormat(format).parse(ts);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str) {
        if (str == null) {
            return null;
        }
        try {
            return parseDate(str.toString(), parsePatterns);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate() {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算两个时间差
     */
    public static String getDatePoor(Date endDate, Date nowDate) {
        long nd = (long) 1000 * 24 * 60 * 60;
        long nh = (long) 1000 * 60 * 60;
        long nm = (long) 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    /**
     * 获取当前日期是星期几<br>
     *
     * @param date
     * @return 当前日期是星期几
     */
    public static String getWeekOfDate(Date date) {
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;
        return weekDays[w];
    }

    /**
     * 计算时间
     *
     * @param startTime ： 开始时间
     * @param endTime   ： 结束时间
     * @return
     */
    public static int caculateTotalTime(String startTime, String endTime) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date date1 = null;
        Date date = null;
        Long l = 0L;
        try {
            date = formatter.parse(startTime);
            long ts = date.getTime();
            date1 = formatter.parse(endTime);
            long ts1 = date1.getTime();

            l = (ts - ts1) / (1000 * 60 * 60 * 24);

        } catch (ParseException e) {
            log.error("程序异常", e.getMessage());
        }
        return l.intValue();
    }

    /**
     * 判断当前时间是否在规定时间内
     *
     * @param beginTime 开始时间 比如： 08:00
     * @param endTime   结束时间  比如：18:00
     * @return
     */
    public static boolean isTimeSlot(String beginTime, String endTime) {
        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");// 设置日期格式
        Date nowDate = null;
        Date beginDate = null;
        Date endDate = null;
        try {
            nowDate = formatter.parse(formatter.format(new Date()));
            beginDate = formatter.parse(beginTime);
            endDate = formatter.parse(endTime);

            Calendar date = Calendar.getInstance();
            date.setTime(nowDate);

            Calendar begin = Calendar.getInstance();
            begin.setTime(beginDate);

            Calendar end = Calendar.getInstance();
            end.setTime(endDate);

            if (date.after(begin) && date.before(end)) {
                return true;
            } else {
                return false;
            }
        } catch (ParseException e) {
            log.error("程序异常", e.getMessage());
        }
        return true;
    }


    /**
     * 判断当前日期是否在工作日（非工作日：周六，周日）
     *
     * @return
     */
    public static boolean isDatePeriod() {
        Calendar today = Calendar.getInstance();
        //System.out.println("现在时间是 "+sdf.format(today.getTime().getTime()));
        if (today.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || today.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
            //System.out.println("今天是周末");
            return false;
        } else {
            //System.out.println("今天不是周末");
            return true;
        }
    }

    /**
     * 判断指定时间是否在[startTime, endTime]区间，注意时间格式要一致
     *
     * @param nowTime   当前时间
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return
     * @throws ParseException
     * @author jqlin
     */
    public static boolean isEffectiveDate(String nowTime, String beginTime, String endTime) throws ParseException {

        SimpleDateFormat formatter = new SimpleDateFormat("hh:mm");
        Date nowDate = null;
        Date beginDate = null;
        Date endDate = null;

        Calendar date = Calendar.getInstance();
        nowDate = formatter.parse(nowTime);
        date.setTime(nowDate);

        Calendar begin = Calendar.getInstance();
        beginDate = formatter.parse(beginTime);
        begin.setTime(beginDate);

        Calendar end = Calendar.getInstance();
        endDate = formatter.parse(endTime);
        end.setTime(endDate);

        if (date.after(begin) && date.before(end)) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 判断指定当前日期是否在工作日（非工作日：周六，周日）
     *
     * @return
     */
    public static boolean isWeekend(String bDate) throws ParseException {
        DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
        Date bdate = format1.parse(bDate);
        Calendar cal = Calendar.getInstance();
        cal.setTime(bdate);
        if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
            return false;
        } else {
            return true;
        }
    }

    public static boolean isWorkTime() {
        String beginTime = Global.getWorkBeginTime();
        String endTime = Global.getWorkEndTime();
        return DateUtils.isTimeSlot(beginTime, endTime);
    }

    public static Long timeDiff(Date start, Date end) throws ParseException {
        long cha = (end.getTime() - start.getTime()) / (1000 * 60);
        return cha;
    }
}
